package com.lovo.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.common.bean.CommodityBean;
import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.ResponseResult;
import com.lovo.common.result.ResultCode;
import com.lovo.common.util.MQUtil;
import com.lovo.common.util.RedisUtil;
import com.lovo.order.service.IOrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/orders")
@ResponseResult
public class OrderController {
    @Resource
    private IOrderService orderService;
    @Resource
    private MQUtil mqUtil;
    @Resource
    private RedisUtil redisUtil;
    @PostMapping
    public Object add(Long userId,Long commId) throws GlobalHandleException, InvocationTargetException, IllegalAccessException {
        orderService.buy(userId,commId);
        return null;
    }
    @PostMapping("/seckill")
    public Object seckill(Long userId,Long commId){
        mqUtil.send("shop.direct.exchange","seckill_direct_rk",userId+","+commId);
        return null;
    }
    @PutMapping("/updateStatus/{id}")
    public Object updateStatus(@PathVariable("id") String orderId){
        orderService.updateStatus(orderId,1);
        return null;
    }
    @GetMapping("/users/{id}")
    public Object getOrderByUser(@PathVariable("id") Long userId){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        return orderService.list(wrapper);

    }
    // 获取用户是否已经下单成功的方法
    @GetMapping("/status")
    public Object getOrderStatus(Long userId,Long commId) throws GlobalHandleException {
        // 该用户已经下单成功了，返回成功标记，并且把该用户从秒杀缓存中去掉
        if(redisUtil.hget("seckillUser",userId.toString()) != null){
            redisUtil.hdel("seckillUser",userId.toString());
            return null;
        }else{
            // 如果秒杀缓存中没有该用户，则判断库存是否充足，如果库存不足，则返回失败，否则继续等待
            CommodityBean commodityBean = (CommodityBean) redisUtil.get(commId.toString());
            if(commodityBean != null && commodityBean.getCommStock() > 0){
                throw new GlobalHandleException(ResultCode.PLEASE_WAIT);
            }
        }
        throw new GlobalHandleException(ResultCode.COMMODITY_NOT_ENOUGH);
    }

}

